package com.zyl.blog.common.validated;

import com.zyl.blog.common.config.UploadConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;

import java.io.File;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.validated
 * @ClassName: UploadConfigValidator
 * @Description: 上传配置校验器
 * @Author FinalFantasy
 * @Date 2025/3/10-22:20
 */
@Component
@RequiredArgsConstructor
public class UploadConfigValidator implements InitializingBean {

    private final UploadConfig uploadConfig;

    @Override
    public void afterPropertiesSet() {
        validateTempDirectory();
        validateSizeLimits();
    }

    private void validateTempDirectory() {
        File tempDir = new File(uploadConfig.getStorage().getTempDir());
        if (!tempDir.exists() && !tempDir.mkdirs()) {
            throw new IllegalStateException("无法创建临时目录: " + tempDir.getAbsolutePath());
        }
        if (!tempDir.canWrite()) {
            throw new IllegalStateException("临时目录不可写: " + tempDir.getAbsolutePath());
        }
    }

    private void validateSizeLimits() {
        long maxBytes = uploadConfig.getStorage().getMaxFileSize().toBytes();
        if (maxBytes <= 0) {
            throw new IllegalArgumentException("max-file-size必须大于0");
        }
        if (maxBytes > DataSize.ofGigabytes(10).toBytes()) {
            throw new IllegalArgumentException("单文件大小限制不能超过10GB");
        }
    }
}